import { onMounted, onUnmounted, ref } from 'vue'
import { debounce } from 'throttle-debounce-ts'
interface UseScrollOptions {
    throllte?: number
}

export default function useScroll(element?: Window | HTMLLIElement | null) {
    let el: HTMLElement | Window = window 
    const clientHeight = ref<number>(0)
    const scrollTop = ref<number>(0)
    const scrollHeight = ref<number>(0)
    const isBottom = ref<boolean>(false)

    const scrollListener = debounce(10, () => {
        if(el === window) {
            clientHeight.value = document.documentElement.clientHeight
            scrollTop.value = document.documentElement.scrollTop
            scrollHeight.value = document.documentElement.scrollHeight
        } else {
            clientHeight.value = el.clientHeight
            scrollTop.value = el.scrollTop
            scrollHeight.value = el.scrollHeight
        }
        // 判断是否滚动到了底部
        if (scrollHeight.value <= scrollTop.value + clientHeight.value) {
            isBottom.value = true
        }
    })

    onMounted(() => {
        if(element) el = element
        el.addEventListener('scroll', () => scrollListener())
    })

    onMounted(() => {
        el.removeEventListener('scroll', scrollListener)
    })

    return {
        isBottom,
        clientHeight,
        scrollTop,
        scrollHeight
    }
}